import React, { Component, Fragment } from 'react';
import { formatMessage, FormattedMessage } from 'umi/locale';
import { Form, Input, Upload, Select, Button, Icon } from 'antd';
import { connect } from 'dva';
import styles from './BaseView.less';
import GeographicView from '../Comment/GeographicView';
import PhoneView from '../Comment/PhoneView';
// import { getTimeDistance } from '@/utils/utils';

const FormItem = Form.Item;
const { Option } = Select;

const validatorGeographic = (rule, value, callback) => {
  const { province, city, district } = value;
  if (!province.key) {
    callback('请选择省!');
  }
  if (!city.key) {
    callback('请选择市!');
  }
  if (!district.key) {
    callback('请选择区/县!');
  }
  callback();
};

const validatorPhone = (rule, value, callback) => {
  const values = value.split('-');
  if (!values[0]) {
    callback('Please input your area code!');
  }
  if (!values[1]) {
    callback('Please input your phone number!');
  }
  callback();
};

@connect(({ hotel }) => ({
  hotel
}))
@Form.create()
class BaseView extends Component {
  state = {
    previewVisible: false,
    previewImage: '',
    fileList: [],
  }
  componentDidMount() {
    this.setBaseInfo();
  }

  setBaseInfo = () => {
    const { hotel, form } = this.props;
    const fileList = [{
      uid: '-1',
      name: 'xxx.png',
      status: 'done',
      url:hotel.headimgurl
    }];
    this.setState({
      fileList
    });
    Object.keys(form.getFieldsValue()).forEach(key => {
      const obj = {};
      obj[key] = hotel[key] || null;
      form.setFieldsValue(obj);
    });
  };

  handleCancel = () => this.setState({ previewVisible: false })

  handlePreview = (file) => {
    this.setState({
      previewImage: file.url || file.thumbUrl,
      previewVisible: true,
    });
  }

  handleChange = ({ fileList }) => {
    for(let i=0; i<fileList.length; i++){
      if(fileList[i].response && fileList[i].response.status === "SUCCESS" && fileList[i].status === "done"){
        fileList[i]['url'] = fileList[i].response.data
      }
    }
    this.setState({ fileList })
  }

  getViewDom = ref => {
    this.view = ref;
  };

  handleSubmit = () => {
    const { hotel, form, dispatch } = this.props;
    const field = form.getFieldsValue();
    let formData = {};
    formData['address'] = field.address;
    formData['introduce'] = field.introduce;
    formData['name'] = field.name;
    formData['phone'] = field.phone;
    formData['city'] = field.geographic.city.key;
    formData['district'] = field.geographic.district.key;
    formData['province'] = field.geographic.province.key;
    formData['id'] = hotel.id;
    formData['headimgurl'] = this.state.fileList[0].url;

    dispatch({
      type: 'hotel/fetchUpdateHotelInfo',
      payload: formData,
    });
  }

  render() {
    const {
      form: { getFieldDecorator },
    } = this.props;

    return (
      <div ref={this.getViewDom}>
          <Form layout="vertical" onSubmit={this.handleSubmit} hideRequiredMark>
            <FormItem label="列表展示图">
                <Upload 
                  action="/api/api/tool/upload/img"
                  listType="picture-card"
                  name="img"
                  fileList={this.state.fileList}
                  onPreview={this.handlePreview}
                  onChange={this.handleChange}
                >
                  {
                    this.state.fileList.length > 0
                    ?null:
                    <div>
                      <Icon type="plus" />
                      <div className="ant-upload-text">Upload</div>
                    </div>
                  }
                </Upload>
            </FormItem>
            <FormItem label="名称">
              {getFieldDecorator('name', {
                rules: [
                  {
                    required: true,
                    message: '请输入酒店名称',
                  },
                ],
              })(<Input placeholder="酒店名称"/>)}
            </FormItem>
            <FormItem label="简介">
              {getFieldDecorator('introduce', {
                rules: [
                  {
                    required: true,
                    message: "请输入简单介绍",
                  },
                ],
              })(
                <Input.TextArea
                  placeholder="简单介绍"
                  rows={2}
                />
              )}
            </FormItem>
            <FormItem label="所在省市区">
              {getFieldDecorator('geographic', {
                rules: [
                  {
                    required: true,
                    message: '',
                  },
                  {
                    validator: validatorGeographic,
                  },
                ],
              })(<GeographicView />)}
            </FormItem>
            <FormItem label="街道地址">
              {getFieldDecorator('address', {
                rules: [
                  {
                    required: true,
                    message: "请输入街道地址",
                  },
                ],
              })(<Input />)}
            </FormItem>
            <FormItem label="联系电话">
              {getFieldDecorator('phone', {
                rules: [
                  {
                    required: true,
                    message: "请输入联系电话",
                  },
                  { validator: validatorPhone },
                ],
              })(<PhoneView />)}
            </FormItem>
            <Button type="primary" onClick={this.handleSubmit}>
              更新
            </Button>
          </Form>
      </div>
    );
  }
}

export default BaseView;
